package org.goodsmanager.controller;

import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.goodsmanager.entity.User;
import org.goodsmanager.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 认证控制器
 *
 * @author Goods Manager System
 * @version 1.0.0
 */
@Slf4j
@Controller
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final UserService userService;

    /**
     * 跳转到登录页面
     *
     * @return 登录页面
     */
    @GetMapping("/login")
    public String loginPage() {
        return "auth/login";
    }

    /**
     * 跳转到注册页面
     *
     * @return 注册页面
     */
    @GetMapping("/register")
    public String registerPage() {
        return "auth/register";
    }

    /**
     * 处理登录请求
     *
     * @param username 用户名
     * @param password 密码
     * @param session  HttpSession
     * @param redirectAttributes 重定向属性
     * @return 重定向结果
     */
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes redirectAttributes) {
        try {
            User user = userService.login(username, password);
            if (user != null) {
                // 登录成功，将用户信息存储到session中
                session.setAttribute("currentUser", user);
                log.info("用户 {} 登录成功", username);
                return "redirect:/dashboard";
            } else {
                // 登录失败，返回登录页面并显示错误信息
                redirectAttributes.addFlashAttribute("errorMessage", "用户名或密码错误");
                log.warn("用户 {} 登录失败", username);
                return "redirect:/auth/login";
            }
        } catch (Exception e) {
            log.error("登录异常", e);
            redirectAttributes.addFlashAttribute("errorMessage", "登录异常，请稍后重试");
            return "redirect:/auth/login";
        }
    }

    /**
     * 处理注册请求
     *
     * @param user 用户信息
     * @param confirmPassword 确认密码
     * @param redirectAttributes 重定向属性
     * @return 重定向结果
     */
    @PostMapping("/register")
    public String register(User user,
                           @RequestParam String confirmPassword,
                           RedirectAttributes redirectAttributes) {
        try {
            // 检查两次输入的密码是否一致
            if (!user.getPassword().equals(confirmPassword)) {
                redirectAttributes.addFlashAttribute("errorMessage", "两次输入的密码不一致");
                log.warn("用户 {} 注册失败：两次输入的密码不一致", user.getUsername());
                return "redirect:/auth/register";
            }

            // 注册用户
            boolean result = userService.register(user);
            if (result) {
                // 注册成功，跳转到登录页面
                redirectAttributes.addFlashAttribute("successMessage", "注册成功，请登录");
                log.info("用户 {} 注册成功", user.getUsername());
                return "redirect:/auth/login";
            } else {
                // 注册失败，返回注册页面并显示错误信息
                redirectAttributes.addFlashAttribute("errorMessage", "注册失败，用户名可能已存在");
                log.warn("用户 {} 注册失败", user.getUsername());
                return "redirect:/auth/register";
            }
        } catch (Exception e) {
            log.error("注册异常", e);
            redirectAttributes.addFlashAttribute("errorMessage", "注册异常，请稍后重试");
            return "redirect:/auth/register";
        }
    }

    /**
     * 处理登出请求
     *
     * @param session HttpSession
     * @return 重定向到登录页面
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("currentUser");
            if (currentUser != null) {
                session.removeAttribute("currentUser");
                log.info("用户 {} 登出成功", currentUser.getUsername());
            }
        } catch (Exception e) {
            log.error("登出异常", e);
        }
        return "redirect:/auth/login";
    }
}